//
//  PrivateTaxCalcDetailViewController.m
//  PrivateTaxCalculator
//
//  Created by albert ma on 12/21/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "PrivateTaxCalcDetailViewController.h"
#import "CityInsurance.h"
#import "ShareViaWeiboController.h"
#import <sqlite3.h>

static const CLLocationAccuracy DEFAULT_LOCATION = 3000;
static const double REQUEST_LOCATION_TIMEOUT = 30000;
@implementation PrivateTaxCalcDetailViewController
@synthesize belowHalfView;
@synthesize locationActivityIndicator;
@synthesize pensionAmountTextField;
@synthesize pensionRateTextField;
@synthesize medRateTextField;
@synthesize unemployRateTextField;
@synthesize placeTextField;
@synthesize insuranceRateTextField;
@synthesize insuranceAmountTextField;
@synthesize insuranceBaseTextField;
@synthesize insuranceBaseLimitTextField;
@synthesize medAmountTextField;
@synthesize unemployAmountTextField;
@synthesize houseAmountTextField;
@synthesize pensionSwitcher;
@synthesize medSwitcher;
@synthesize unemploySwitcher;
@synthesize houseSwitcher;
@synthesize houseRateTextField;
@synthesize locationManager;
@synthesize privateTaxCalculator;
@synthesize rawIncome;
@synthesize totalInsurance;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        currentTextField_ = nil;
        plackPicker_ = [[UIPickerView alloc]init];
        plackPicker_.dataSource = self;
        plackPicker_.delegate = self;
        plackPicker_.showsSelectionIndicator = YES;
        cityArray = [[NSMutableArray alloc] init];
    }
    return self;
}


- (void)dealloc
{
    [pensionRateTextField release];
    [medRateTextField release];
    [unemployRateTextField release];
    [houseRateTextField release];
    [belowHalfView release];

    [locationManager release];
    [placeTextField release];
    [plackPicker_ release];
    [cityArray release];

    [insuranceRateTextField release];
    [insuranceAmountTextField release];
    [insuranceBaseTextField release];
    [insuranceBaseLimitTextField release];
    [pensionAmountTextField release];
    [medAmountTextField release];
    [unemployAmountTextField release];
    [houseAmountTextField release];
    [pensionSwitcher release];
    [medSwitcher release];
    [unemploySwitcher release];
    [houseSwitcher release];
    [privateTaxCalculator release];
    [rawIncome release];
    [locationActivityIndicator release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (BOOL)needMoveBelowView
{
    if (currentTextField_ == self.pensionRateTextField ||
        currentTextField_ == self.medRateTextField ||
        currentTextField_ == self.houseRateTextField ||
        currentTextField_ == self.unemployRateTextField) {
        return TRUE;
    } else {
        return FALSE;
    }
}

- (void)keyboardWillShown:(NSNotification *)notification
{
    if ([self needMoveBelowView]) {
        double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        belowHalfView.alpha = 0;
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:duration];
        [UIView setAnimationDelegate:self];
        belowHalfView.frame = CGRectMake(0, 0, 320, 230);
        belowHalfView.alpha = 1.0;
        [UIView commitAnimations];
    }
}

- (void) keyboardWillHide:(NSNotification *)notification 
{
    if ([self needMoveBelowView]) {
        double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:duration];
        [UIView setAnimationDelegate:self];
        belowHalfView.frame = CGRectMake(0, 230, 320, 230);
        [UIView commitAnimations];
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    [self loadCityData];
    [self.insuranceAmountTextField setText:[NSString stringWithFormat:@"%.2f", [self.totalInsurance doubleValue]]];
    
    if (locationManager == nil) 
    {
        CLLocationManager *locationMgr = [[CLLocationManager alloc] init];
        self.locationManager = locationMgr;
        [locationMgr release];
    }
    if([CLLocationManager locationServicesEnabled] == YES)
    {
        [locationActivityIndicator setHidden:NO];
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
        [locationManager startUpdatingLocation];
        
        [self performSelector:@selector(stopUpdatingLocation:)withObject:@"超时" afterDelay:REQUEST_LOCATION_TIMEOUT];
               
    }
    else
    {
        [locationActivityIndicator setHidden:YES];
        UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"定位服务未开启" message:@"如果想使用自动定位，请在设置中开启定位功能" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [serviceDisableAlert show];
        [serviceDisableAlert release];
    }
    
    
    UIImage* paper = [UIImage imageNamed:@"paper_material"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:paper];
    self.belowHalfView.backgroundColor = [UIColor colorWithPatternImage:paper];
    self.placeTextField.inputView = plackPicker_;

}


- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self setPensionRateTextField:nil];
    [self setMedRateTextField:nil];
    [self setUnemployRateTextField:nil];
    [self setHouseRateTextField:nil];
    [self setBelowHalfView:nil];

   
    [self setPlaceTextField:nil];

    [self setInsuranceRateTextField:nil];
    [self setInsuranceAmountTextField:nil];
    [self setInsuranceBaseTextField:nil];
    [self setInsuranceBaseLimitTextField:nil];
    [self setPensionAmountTextField:nil];
    [self setMedAmountTextField:nil];
    [self setUnemployAmountTextField:nil];
    [self setHouseAmountTextField:nil];
    [self setPensionSwitcher:nil];
    [self setMedSwitcher:nil];
    [self setUnemploySwitcher:nil];
    [self setHouseSwitcher:nil];
    [self setLocationActivityIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}



- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    currentTextField_ = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    currentTextField_ = textField;
}
							
- (IBAction)gotoShareView:(id)sender {
    NSString *insuranceAmount = [self.insuranceAmountTextField text];
    if(insuranceAmount == nil ||[insuranceAmount length] == 0)
    {
        
        UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先计算结果再分享" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [serviceDisableAlert show];
        [serviceDisableAlert release];
        return;
    }
    NSString* medAmount = [self.medAmountTextField text];
    NSString* pensionAmount = [self.pensionAmountTextField text];
    NSString* houseAmount =[self.houseAmountTextField text];
    NSString* unemployAmount = [self.unemployAmountTextField text];
    NSString* insurenceTotalAmount =[self.insuranceAmountTextField text];
    double insuranceTotalDouble = [insurenceTotalAmount doubleValue];
   
    double tax = -1;
    if(self.privateTaxCalculator != nil && rawIncome != nil)
    {
        double rawIncomeDouble = [rawIncome doubleValue];
        tax = [privateTaxCalculator getTax:rawIncomeDouble insurance:insuranceTotalDouble withType:TAX_2011];
        
       
    }
    ShareViaWeiboController* sharedController = [[[ShareViaWeiboController alloc] initWithNibName:@"ShareViaWeiboController" bundle:nil] autorelease];
    
    NSMutableString *shareContent = [[NSMutableString alloc] init];
    
    [shareContent appendString:[NSString stringWithFormat:@"#晒三险一金/#我每月的三险一金个人部分 医保:%@,失业保险%@, 养老保险%@, 住房公积金%@", medAmount, unemployAmount, pensionAmount, houseAmount]];
    if(tax >= 0)
    {
        [shareContent appendString:[NSString stringWithFormat:@" 缴税:%.2f", tax]];
    }
    [sharedController setSharedContent:shareContent];
    [shareContent release];
    [self.navigationController pushViewController:sharedController animated:YES];
}

- (IBAction)backButtonClicked:(id)sender 
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)touchScreen:(id)sender 
{
    [self.view endEditing:YES];
}

- (IBAction)calculateInsurance:(id)sender 
{
    [self performSelector:@selector(calculateInsuranceValue)];
}

-(void)calculateInsuranceValue
{
    NSString* amountString = [self.insuranceBaseTextField text];
    if([amountString length]  == 0)
    {
        UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"输入交费基数" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [serviceDisableAlert show];
        [serviceDisableAlert release];
        return;
    }
    double insuranceBaseValue = [[self.insuranceBaseTextField text] doubleValue];
    if(insuranceBaseValue == 0)
    {
        
        UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"输入交费基数等于0" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [serviceDisableAlert show];
        [serviceDisableAlert release];
        
        return;
    }
    
    
    double pensionRate = [[self.pensionRateTextField text] doubleValue] /100.00;
    double houseRate =[[self.houseRateTextField text]doubleValue] / 100.00;
    double medRate = [[self.medRateTextField text]doubleValue] /100.00;
    double unemployRate =[[self.unemployRateTextField text]doubleValue] /100.00;
    double totalRate = pensionRate + houseRate + medRate + unemployRate;
    NSString* totalRateStr = [NSString stringWithFormat:@"%.2f", totalRate * 100];
    
    int isPensionLimitOff = [self.pensionSwitcher selectedSegmentIndex];
    int isHouseLimitOff = [self.houseSwitcher selectedSegmentIndex];
    int isMedLimitOff = [self.medSwitcher selectedSegmentIndex];
    int isUnemployOff = [self.unemploySwitcher selectedSegmentIndex];
    
    double insuranceBaseLimit = [[self.insuranceBaseLimitTextField text] doubleValue];
    
    double pensionBaseLimit = isPensionLimitOff == 0 &&  insuranceBaseValue >= insuranceBaseLimit? insuranceBaseLimit: insuranceBaseValue;
    
    double medBaseLimit = isMedLimitOff == 0 &&  insuranceBaseValue >= insuranceBaseLimit? insuranceBaseLimit: insuranceBaseValue;
    
    double houseBaseLimit = isHouseLimitOff == 0 &&  insuranceBaseValue >= insuranceBaseLimit? insuranceBaseLimit: insuranceBaseValue;
    
    double unemployBaseLimit = isUnemployOff == 0 &&  insuranceBaseValue >= insuranceBaseLimit? insuranceBaseLimit: insuranceBaseValue;
    
    double pensionInsurance = pensionRate * pensionBaseLimit;
    double unemployInsurance = unemployRate * unemployBaseLimit;
    double houseFund = houseRate * houseBaseLimit;
    double medInsurance = medRate * medBaseLimit;
    double insuranceTotal = pensionInsurance + unemployInsurance + houseFund + medInsurance;
    [self.medAmountTextField setText:[NSString stringWithFormat:@"%.2f", medInsurance]];
    [self.pensionAmountTextField setText:[NSString stringWithFormat:@"%.2f", pensionInsurance]];
    [self.houseAmountTextField setText:[NSString stringWithFormat:@"%.2f", houseFund]];
    [self.unemployAmountTextField setText:[NSString stringWithFormat:@"%.2f", unemployInsurance]];
    [self.insuranceAmountTextField setText:[NSString stringWithFormat:@"%.2f", insuranceTotal]];
    [insuranceRateTextField setText:totalRateStr];

}

#pragma mark picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [cityArray count];
}


#pragma mark picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    CityInsurance* cityInsurance = [cityArray objectAtIndex: row];
    return [cityInsurance cityName];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    CityInsurance* cityInsurance = [cityArray objectAtIndex: row];
    [self.placeTextField setText: [cityInsurance cityName]];
    double insuranceRateValue = [[cityInsurance houseRate] doubleValue] + [[cityInsurance pensionRate]doubleValue] 
        + [[cityInsurance medRate]doubleValue] + [[cityInsurance umemployRate] doubleValue];
    NSString *rateText = [NSString stringWithFormat:@"%.2f", insuranceRateValue * 100];
    NSString *pensionText =[NSString stringWithFormat:@"%.2f", [[cityInsurance pensionRate]doubleValue]  * 100];
    NSString *medText =[NSString stringWithFormat:@"%.2f", [[cityInsurance medRate]doubleValue]  * 100];
    NSString *houseText =[NSString stringWithFormat:@"%.2f", [[cityInsurance houseRate] doubleValue] * 100];
    NSString *unemployText =[NSString stringWithFormat:@"%.2f", [[cityInsurance umemployRate] doubleValue] * 100];
    NSString *insuracneBaseLimit = [NSString stringWithFormat:@"%.2f",[[cityInsurance umemployBaseLimit] doubleValue]];
    NSString *insuranceBase = [NSString stringWithFormat:@"%.2f",[self.privateTaxCalculator getInsuranceBase:[self.totalInsurance doubleValue] withInsuranceRate:insuranceRateValue]];
    [self.insuranceRateTextField setText:rateText];
    [self.pensionRateTextField setText:pensionText];
    [self.medRateTextField setText:medText];
    [self.houseRateTextField setText:houseText];
    [self.unemployRateTextField setText:unemployText];
    [self.insuranceBaseLimitTextField setText:insuracneBaseLimit];
    [self.insuranceBaseTextField setText:insuranceBase];
    [self performSelector:@selector(calculateInsuranceValue)];
}

#pragma mark reverse geocoder
-(void)reverseGeoCoder:(CLLocation *) currentLocation
{
    CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) 
     {
         BOOL isFind = NO;
         [locationActivityIndicator setHidden:YES];
         NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
         if (error){
             
             NSLog(@"Geocode failed with error: %@", error);
             
             return;
         }
         NSLog(@"Received placemarks: %@", placemarks);
         NSMutableString *totalString = [[NSMutableString alloc] init];
         
         for(CLPlacemark *text in placemarks)
         {
             NSLog(@"reverse geocoder: %@", text);
             NSString *currentText = [NSString stringWithFormat:@"%@",text];
             if(currentText != nil)
             {
                 [totalString appendString:currentText];
             }
         }
         
         for (CityInsurance* cityInsurance in cityArray) 
         {
             
             NSRange range = [totalString rangeOfString :[cityInsurance cityName]];
             if(range.location != NSNotFound)
             {
                 isFind = YES;
                 double insuranceRateValue = [[cityInsurance houseRate] doubleValue] + [[cityInsurance pensionRate]doubleValue] 
                 + [[cityInsurance medRate]doubleValue] + [[cityInsurance umemployRate] doubleValue];
                 NSString *rateText = [NSString stringWithFormat:@"%.2f", insuranceRateValue * 100];
                 NSString *pensionText =[NSString stringWithFormat:@"%.2f", [[cityInsurance pensionRate]doubleValue]  * 100];
                 NSString *medText =[NSString stringWithFormat:@"%.2f", [[cityInsurance medRate]doubleValue]  * 100];
                 NSString *houseText =[NSString stringWithFormat:@"%.2f", [[cityInsurance houseRate] doubleValue] * 100];
                 NSString *unemployText =[NSString stringWithFormat:@"%.2f", [[cityInsurance umemployRate] doubleValue] * 100];
                 NSString *insuracneBaseLimit = [NSString stringWithFormat:@"%.2f",[[cityInsurance umemployBaseLimit] doubleValue]];
                  NSString *insuranceBase = [NSString stringWithFormat:@"%.2f",[self.privateTaxCalculator getInsuranceBase:[self.totalInsurance doubleValue] withInsuranceRate:insuranceRateValue]];
                 [self.placeTextField setText:[cityInsurance cityName]];
                 [self.insuranceRateTextField setText:rateText];
                 [self.pensionRateTextField setText:pensionText];
                 [self.medRateTextField setText:medText];
                 [self.houseRateTextField setText:houseText];
                 [self.unemployRateTextField setText:unemployText];
                 [self.insuranceBaseLimitTextField setText:insuracneBaseLimit];
                 [self.insuranceBaseTextField setText:insuranceBase];
                 [self performSelector:@selector(calculateInsuranceValue)];
                 
                 break;
             }
             
         }
         [totalString release];
         if (!isFind) {
             UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"数据库中没有您城市的资料，请手动输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [serviceDisableAlert show];
             [serviceDisableAlert release];
         }
         
     }];
    
}

#pragma mark CLLocationManagerDelegate Methods
- (void)stopUpdatingLocations:(NSString *)state
{
    [locationManager stopUpdatingLocation];
    locationManager.delegate = nil;
    if (![state isEqualToString:@"gotLocation"]) {
        [locationActivityIndicator setHidden:YES];
    }
    
    NSLog(@"Location request is stop for reason of %@", state);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // The location "unknown" error simply means the manager is currently unable to get the location.
    // We can ignore this error for the scenario of getting a single location fix, because we already have a 
    // timeout that will stop the location manager to save power.
    if ([error code] != kCLErrorLocationUnknown) {
        [self stopUpdatingLocations:NSLocalizedString(@"Error", @"Error")];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if (newLocation != nil) {
        
        NSLog(@"New Location latitude: %f, longtitude: %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
        //query city from location, set corresponding tax data
      //  [self performSelector:@selector(reverseGeoCoder) withObject:newLocation];
        [self reverseGeoCoder:newLocation];
        if([self respondsToSelector:@selector(stopUpdatingLocations:)]){
            [self performSelector:@selector(stopUpdatingLocations:) withObject:@"gotLocation"];
        }else {
            NSLog(@"no selector");
        }

        
    }
}


#pragma mark load data from sql table
- (void)loadCityData
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	NSString*dbPath= [documentsDir stringByAppendingPathComponent:@"tax_rate.sqlite"];
    static sqlite3 *database = nil;
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		const char *sql = "select city, minLatitude, minLongitude, maxLatitude, maxLongitude, house_rate, house_base_limit, pension_rate,pension_base_limit, med_rate, med_base_limit, unemploy_rate, unemploy_base_limit  from insurance_city_table";
		sqlite3_stmt *selectstmt;
		if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
			
			while(sqlite3_step(selectstmt) == SQLITE_ROW) {

                CityInsurance *cityInsurance = [[CityInsurance alloc]init];
                [cityInsurance setCityName:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)]];
                [cityInsurance setMinLat:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 1)]];
                [cityInsurance setMinLon:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 2)]];
                [cityInsurance setMaxLat:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 3)]];
                [cityInsurance setMaxLon:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 4)]];
                
                [cityInsurance setHouseRate:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 5)]];
                [cityInsurance setHouseBaseLimit:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 6)]];
                
                [cityInsurance setPensionRate:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 7)]];
                [cityInsurance setPensionBaseLimit:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 8)]];

                [cityInsurance setMedRate:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 9)]];
                [cityInsurance setMedBaseLimit:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 10)]];
                
                [cityInsurance setUmemployRate:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 11)]];
                [cityInsurance setUmemployBaseLimit:[NSNumber numberWithDouble:sqlite3_column_double(selectstmt, 12)]];


                [cityArray addObject:cityInsurance];
                [cityInsurance release];
            }
		}
    }
    
    sqlite3_close(database);
    

}


@end
